package com.idanchuang.component.logback.util;

import com.alibaba.fastjson.serializer.ValueFilter;
import com.idanchuang.component.logback.annotation.MaskInLog;

import java.lang.reflect.Field;
import java.util.Map;

public class MaskValueFilter implements ValueFilter {

    @Override
    public Object process(Object o, String s, Object o1) {
        if (o1 == null) {
            return null;
        }
        try {
            if (Map.class.isAssignableFrom(o.getClass())) {
                return o1;
            }
            Field field = o.getClass().getDeclaredField(s);
            if (field.isAnnotationPresent(MaskInLog.class)) {
                MaskInLog maskInLog = field.getAnnotation(MaskInLog.class);
                return LogUtil.mask(o1.toString(), maskInLog.value());
            }
        } catch (NoSuchFieldException e) {
            // ignore
        } catch (Exception e) {
            e.printStackTrace();
        }
        return o1;
    }

}
